package com.md.util;

import com.md.base.exception.ServerException;
import com.md.value.enums.ErrorEnum;
import lombok.experimental.UtilityClass;
import lombok.extern.slf4j.Slf4j;
import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.HanyuPinyinVCharType;
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;

import static com.md.util.MatchUtil.isChinese;

/**
 * @author 刘骄阳
 * 2024-06-11 10:59
 */
@Slf4j
@UtilityClass
public class PinYinUtil {
  private static final HanyuPinyinOutputFormat OUTPUT_FORMAT = new HanyuPinyinOutputFormat();

  private void buildOutputFormat() {
    // 小写
    OUTPUT_FORMAT.setCaseType(HanyuPinyinCaseType.LOWERCASE);
    OUTPUT_FORMAT.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
    // 不带声调
    OUTPUT_FORMAT.setVCharType(HanyuPinyinVCharType.WITH_V);
  }


  /**
   * 汉字转全拼
   *
   * @param value 汉字字符串
   * @return 全拼字符串
   */
  public static String getPinyin(final String value) {
    if (ObjectUtil.isEmpty(value)) {
      return "";
    }
    StringBuilder result = new StringBuilder();
    char[] chars = value.toCharArray();
    for (char word : chars) {
      try {
        if (isChinese(word)) {
          String[] pinyinArray = PinyinHelper.toHanyuPinyinStringArray(word, OUTPUT_FORMAT);
          if (ObjectUtil.notEmpty(pinyinArray)) {
            result.append(pinyinArray[0]);
          }
        } else {
          // 非拼音直接追加
          result.append(word);
        }
      } catch (BadHanyuPinyinOutputFormatCombination e) {
        log.error("拼音解析异常: {}", e.getMessage(), e);
        throw ServerException.build(ErrorEnum.SERIALIZE_PINYIN_ERROR);
      }
    }
    return result.toString();
  }

  /**
   * 汉字转简拼
   *
   * @param value
   * @return String
   */
  public static String getPinYinHeadChar(final String value) {
    if (ObjectUtil.isEmpty(value)) {
      return "";
    }
    StringBuilder result = new StringBuilder();
    int length = value.length();
    for (int j = 0; j < length; j++) {
      try {
        char word = value.charAt(j);
        if (isChinese(word)) {
          // 提取汉字的首字母
          String[] pinyinArray = PinyinHelper.toHanyuPinyinStringArray(word, OUTPUT_FORMAT);
          if (ObjectUtil.notEmpty(pinyinArray)) {
            result.append(pinyinArray[0].charAt(0));
          } else {
            // 非拼音直接追加
            result.append(word);
          }
        } else {
          // 非拼音直接追加
          result.append(word);
        }
      } catch (BadHanyuPinyinOutputFormatCombination e) {
        log.error("拼音解析异常: {}", e.getMessage(), e);
        throw ServerException.build(ErrorEnum.SERIALIZE_PINYIN_ERROR);
      }
    }
    return result.toString();
  }
}
